<?php

namespace App\Controllers;

use CodeIgniter\Controller;
use Config\App;

/**
 * Our base controller.
 */
class Application extends Controller {
	protected $data = []; // parameters for view components
	protected $id; // identifier for our content
	protected $parser;
	protected $encrypter;
	protected $session;
	protected $setting;
	protected $userModel;
	protected $user;

	/**
	 * Constructor.
	 * Establish view parameters & set a couple up
	 */
	public function __construct(...$params) {
        //parent::__construct(...$params);
		$this->config = new \Config\App();
		$this->loader = new \CodeIgniter\Autoloader\FileLocator(new \Config\Autoload());
		$this->viewsDir = __DIR__ . '/Views';
		$this->data = [];

		$this->errors = [];

		$this->db = \Config\Database::connect();
		$this->db->initialize();

		$this->cache = \Config\Services::cache();
		$this->request = \Config\Services::request();
		$this->encrypter = \Config\Services::encrypter(['driver' => 'OpenSSL']);

		$this->session = session();
        if (session_status() == PHP_SESSION_NONE)  {
            // session has not started so start it
            $this->session->start();
        }

		$this->setting = new \App\Models\SettingsModel();

		$this->data['homeTitle'] = $this->setting->getSetting('title');
		$this->data['metaDesc'] = $this->setting->getSetting('metaDesc') ?: '';
		$this->userModel = new \App\Models\UserModel();
		$this->user = $this->userModel->checkLogin();
		if ($this->user) {
			$this->data['user'] = $this->user;
		}

	}

	/**
	 * @param array 0:content,1:page
	 */
	public function render($page, $title = "", $header = "default") {
		$this->data['title'] = $title;

		$app = new App();
		$this->data['assets'] = $app->baseURL . "assets";

		$this->data['content'] = view($page, $this->data);

		if (!$this->request->isAJAX() && $header) {
			echo view($header, $this->data);
		} else {
			echo $this->data['content'];
		}
	}

	/**
	 * return json string
	 *
	 * @param string|array $message
	 * @param string $status
	 */
	public function showJson($message = '', $status = '') {
		$array = [];
		if ($status && !is_array($message)) {
			$array['status'] = $status;
			$array['message'] = $message;
		} else {
			$array = $message;
		}
		echo json_encode($array, JSON_UNESCAPED_UNICODE);
		exit();
	}

	/**
	 * @param string $message
	 * @param string $url
	 */
	public function showError($message = '', $url = '') {
		$data['message'] = $message;
		$data['url'] = $url ?: $this->config->baseURL;
		echo view('errors/html/error', $data);
		exit(1);
	}
}
